package org.sample.controller;

import org.sample.model.APIResult;
import org.sample.dao.ConfigDao;
import org.sample.entity.Config;
import org.sample.entity.enums.CheckState;
import org.sample.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("manage/config")
public class ConfigController {

    @Autowired
    private ConfigDao configDao;

    @Autowired
    private ConfigService configService;

    @RequestMapping(path = {"edit", "add"}, method = RequestMethod.GET)
    public String edit(Config entity, Model model) {
        Integer id = 1;
        if (id != null) {
            entity = configDao.getOne(id);
        }
        initPageParam(model);
        model.addAttribute("entity", entity);
        return "config/edit";
    }

    @RequestMapping(path = "update", method = RequestMethod.POST)
    public String update(Config entity) {
        configService.saveNotNull(entity);
        return "redirect:edit?id=" + entity.getId();
    }

    @RequestMapping(path = "remove", method = RequestMethod.POST)
    @ResponseBody
    public APIResult remove(Integer id) {
        configService.logicalDelete(id);
        return new APIResult();
    }

    @RequestMapping("list")
    public String list(@RequestParam(required = false, defaultValue = "1") int pageNo,
                       @RequestParam(required = false, defaultValue = "10") int pageSize,
                       Config entity, Model model) {
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize);
        Page<Config> page = configDao.findAll(Example.of(entity), pageable);
        model.addAttribute("page", page);

        initPageParam(model);

        model.addAttribute("entity", entity);
        return "config/list";
    }

    private void initPageParam(Model model) {
        List<Config> configs = configService.getIdNameList();
        model.addAttribute("configs", configs);

        CheckState[] checkStates = CheckState.values();
        model.addAttribute("checkStates", checkStates);
    }

}